/**
 * 简化版BullMQ队列配置
 * 专门用于解决net::ERR_CONNECTION_RESET问题
 * 使用CommonJS格式，兼容现有系统
 */

const { Queue } = require('bullmq');
const Redis = require('ioredis');

// Redis连接配置
const REDIS_CONFIG = {
  host: process.env.REDIS_HOST || 'localhost',
  port: parseInt(process.env.REDIS_PORT) || 6379,
  maxRetriesPerRequest: 3,
  retryDelayOnFailover: 100,
  lazyConnect: true
};

// 创建Redis连接
const redisConnection = new Redis(REDIS_CONFIG);

// 队列配置
const QUEUE_CONFIG = {
  aiInference: {
    name: 'ai-inference-queue',
    defaultJobOptions: {
      removeOnComplete: 100, // 保留最近100个完成的任务
      removeOnFail: 50,      // 保留最近50个失败的任务
      attempts: 2,           // 默认重试2次
      backoff: {
        type: 'exponential',
        delay: 2000
      },
      delay: 0,              // 不延迟
      priority: 0            // 默认优先级
    }
  }
};

// 创建队列实例
const aiInferenceQueue = new Queue(QUEUE_CONFIG.aiInference.name, {
  connection: redisConnection,
  defaultJobOptions: QUEUE_CONFIG.aiInference.defaultJobOptions
});

// 初始化队列系统
async function initializeQueues() {
  try {
    console.log('🔄 初始化简化版队列系统...');

    // 测试Redis连接
    await redisConnection.ping();
    console.log('✅ Redis连接成功');

    console.log('✅ 简化版队列系统初始化完成');
    return true;

  } catch (error) {
    console.error('❌ 队列系统初始化失败:', error);

    // 如果Redis不可用，系统降级运行
    if (error.code === 'ECONNREFUSED') {
      console.warn('⚠️ Redis不可用，系统将降级运行，AI推理任务将同步执行');
      return false;
    }

    throw error;
  }
}

// 添加AI推理任务
async function addAIInferenceTask(taskData, options = {}) {
  try {
    const job = await aiInferenceQueue.add(
      'ai-inference',
      taskData,
      {
        priority: options.priority || 0,
        delay: options.delay || 0,
        attempts: options.attempts || 2,
        ...options
      }
    );

    console.log(`📤 AI推理任务已添加到队列: ${job.id}`);
    return job;

  } catch (error) {
    console.error('添加AI推理任务失败:', error);
    throw error;
  }
}

// 获取任务状态
async function getJobStatus(jobId) {
  try {
    const job = await aiInferenceQueue.getJob(jobId);

    if (!job) {
      return { status: 'not_found' };
    }

    const state = await job.getState();
    const progress = job.progress;

    return {
      id: job.id,
      data: job.data,
      status: state,
      progress,
      createdAt: job.timestamp,
      processedAt: job.processedOn,
      finishedAt: job.finishedOn,
      failedReason: job.failedReason,
      returnvalue: job.returnvalue
    };

  } catch (error) {
    console.error('获取任务状态失败:', error);
    return { status: 'error', error: error.message };
  }
}

// 获取队列统计信息
async function getQueueStats() {
  try {
    const waiting = await aiInferenceQueue.getWaiting();
    const active = await aiInferenceQueue.getActive();
    const completed = await aiInferenceQueue.getCompleted();
    const failed = await aiInferenceQueue.getFailed();
    const delayed = await aiInferenceQueue.getDelayed();

    return {
      waiting: waiting.length,
      active: active.length,
      completed: completed.length,
      failed: failed.length,
      delayed: delayed.length,
      total: waiting.length + active.length + completed.length + failed.length + delayed.length
    };

  } catch (error) {
    console.error('获取队列统计失败:', error);
    return {
      waiting: 0,
      active: 0,
      completed: 0,
      failed: 0,
      delayed: 0,
      total: 0,
      error: error.message
    };
  }
}

// 关闭队列系统
async function closeQueues() {
  try {
    console.log('🛑 关闭简化版队列系统...');

    await aiInferenceQueue.close();
    await redisConnection.quit();

    console.log('✅ 简化版队列系统已关闭');
  } catch (error) {
    console.error('关闭队列系统失败:', error);
  }
}

// 检查Redis可用性
async function checkRedisAvailability() {
  try {
    await redisConnection.ping();
    return true;
  } catch (error) {
    return false;
  }
}

// 优雅关闭处理
process.on('SIGINT', closeQueues);
process.on('SIGTERM', closeQueues);

module.exports = {
  initializeQueues,
  addAIInferenceTask,
  getJobStatus,
  getQueueStats,
  closeQueues,
  checkRedisAvailability,
  queues: {
    aiInference: aiInferenceQueue
  },
  REDIS_CONFIG,
  QUEUE_CONFIG
};